# coding=utf-8
# 第一版 2022/3/21 author: ylong52@21cn.com
from http import server
from lib2to3.pgen2 import driver
from urllib.parse import urlparse
from myselenium import *
import sys
from LocalStorage import *
from browsermobproxy import Server
from weblogin import * 
import json

class artMain:
    #解决占用端口
    def kill_process(self,port):
        # os.system('taskkill /im chromedriver.exe /F')
        # os.system('taskkill /im chrome.exe /F')

        ret = os.popen("netstat -nao|findstr '"+str(port)+"'")    
        #注意解码方式和cmd要相同，即为"gbk"，否则输出乱码
        str_list = ret.read() 
        time.sleep(0.5)
        ret_list = re.split('',str_list)
        try:
            process_pid = list(ret_list[0].split())[-1]
            os.popen('taskkill /pid ' + str(process_pid) + ' /F')
            print("端口已被释放")
        except:
            #print("端口未被使用")
            return True

    #读ini文件  
    def getGoodINIUrl(self):
        cfg1 = "./config_scan_ids.ini"
        conf = configparser.ConfigParser()
        conf.read(cfg1, encoding="utf-8-sig")
        self.config = conf

        cfg2 = self.config.get("setup", "loginfile")
        conf2 = configparser.ConfigParser()
        conf2.read(cfg2, encoding="utf-8-sig")
        self.logconfig = conf2


    #主程序
    def __init__(self):              
        self.scanmain()
                
    def scanmain(self):
        self.getGoodINIUrl()  
        if os.path.exists("logs.txt"):
            os.remove("logs.txt")

        dict={'port':8090} #browsermob-proxy端口
        self.kill_process(8090);
        try:
            sserver = Server(r".\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat",options=dict)                
            sserver.start()
        except:
            self.kill_process(8090);
            sserver.start()

        proxy = sserver.create_proxy()    
        self.proxy = proxy
        chrome_options2 = Options()
        if ("1" != self.config.get("setup", "viewgoogle")):
            chrome_options2.add_argument('--headless') #无头浏览器

        # chrome_options2.add_argument('--disable-gpu')
        chrome_options2.add_argument('--ignore-certificate-errors')
        chrome_options2.add_argument('--ignore-ssl-errors')
        chrome_options2.add_argument('--proxy-server={0}'.format(proxy.proxy))
        chrome_options2.add_argument("--auto-open-devtools-for-tabs")
        chrome_options2.add_argument("--enable-web-app-frame")
        # chrome_options2.add_argument("--disable-extensions")
        chrome_options2.add_argument("--enable-mobile-emulation")

        #手机模式
        WIDTH = 600
        HEIGHT = 1452
        PIXEL_RATIO =2.0
        # UA 必须要是手机设备的
        UA = 'Mozilla/5.0 (Linux; Android 4.1.1; GT-N7100 Build/JRO03C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/6.3'
        mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO}, "userAgent": UA}
        # chrome_options2.add_experimental_option("mobileEmulation", mobileEmulation)        
        chrome_options2.add_experimental_option('mobileEmulation', mobileEmulation)   
        

        # mobileEmulation = {"deviceName": "iPad Air"}
        # chrome_options2.add_experimental_option("mobileEmulation", mobileEmulation)        

        # prefs = {"profile.managed_default_content_settings.images": 2}
        # chrome_options2.add_experimental_option("prefs", prefs)

        # driver = webdriver.Chrome(options=chrome_options2)
        # chrome_options2 = DebugBrowser().debug_chrome(proxy);  #只启动一个google调试
        driver=webdriver.Chrome(options=chrome_options2)
 
 
        driver.get('https://artmeta.cn/')
        time.sleep(2)

        self.driver = driver
        self.loginAccount()


    def loginAccount(self):        
        storage = LocalStorage(self.driver)
        _setion = "login";
        storage["truename"] = self.logconfig.get(_setion, "truename")
        storage["UserLoginToken"] = self.logconfig.get(_setion, "UserLoginToken")
        storage["userinfo"] =  self.logconfig.get(_setion, "userinfo")       
        print('登录中......')
 
        self.driver.get('https://artmeta.cn/pages/usercenter/usercenter')
        
        print(self.driver.title)
        time.sleep(1)
        if(storage.get("truename")==None):
            print('帐号登录登录失败!!!!!')             
            self.driver.quit()
            os._exit(0)
        else:
            print('帐号登录成功 >>>')
            xLoop = True
            while xLoop:
                self.decomposeGroupIDs()
                print("完成一次循环 ￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣ \n")
                time.sleep(0.5)

    def decomposeGroupIDs(self):
        group_ids = self.config.get("goods", "group-ids")
        ids = group_ids.split(",")        
        for i in ids:
            a = ids.index(i)  
            bs2 = ids[a].split("-")   #bs2是分组的['180750', '180770']
            _iStart = to_int(bs2[0])
            while _iStart <= to_int(bs2[1]):
                _url = "https://artmeta.cn/pages/worksdetail/worksdetail?id="+str(_iStart)
                self.derivativedetail(_url)
                _iStart = _iStart +1 
               
            return True  
        
    
 

            
 
    #找到转售市场
    def derivativedetail(self,_url):
        print("url="+_url)
        self.proxy.new_har("huaruntong2", options={'captureHeaders': True, 'captureContent': True})
        self.driver.get(_url)
        time.sleep(0.5)
        self.__getHarUrl2(self.proxy.har)
        # time.sleep(100)
            
            

    #取包
    def __getHarUrl2(self,result):
        # print("line 145") 
        # print(result)
        _find = 0
        for entry in result['log']['entries']:
            _url = entry['request']['url']
            if "api.artmeta.cn/api.ashx" in _url:
                # print("line 241, >>>>>>>>>>"+_url+">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
                _response = entry['response']
                _content = _response['content']               
                # print(_url)
                if "PublishUserInfo" in json.dumps(_content):
                    # print("line:158,>>>")
                    # print(_content)
                    _find = 1
                    self.__dataout2(_content)

        if (_find==0):        
            print("一件商品也没有找到    >>>>>>>> \n")
                

    
    ##分析接口数据
    def __dataout2(self,data):
        s_myPrice = self.config.get("goods","price")  #最低的价格
        
        # print("_filter_price = ")
        # print(_filter_price)
        #json.dumps将python对象格式化成json字符（将dict转化成str）
        #json.loads将json字符串解码成python对象（将str转化成dict）
        _dict = json.loads(data['text'])
        _data = _dict.get('Data')    #datalist是dict类型 

        astr = "No. id:"+str(_data['GoodsId'])+",name:"+_data['GoodsName']+",price:"+str(_data['GoodsPrice'])+",my price:"+s_myPrice
        print(astr)
        if (to_int(_data['GoodsPrice'])>0 and to_int(_data['GoodsPrice']) <= to_int(s_myPrice)):
            self._buynow()
        # os._exit(0)

        # for i in _datalist:
        #     #print("id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice'])+"\n")

        #     astr = "No."+str(_countList)+",id:"+str(i['GoodsId'])+",name:"+i['GoodsName']+",price:"+str(i['GoodsPrice'])
        #     print(astr)
        #     with open('logs.txt','a',encoding="utf-8") as file:
        #         file.write(astr+"\n")

        # print("\n\n")
        # self.countList = _countList
        # if (_find_num==0 and _filter_price>0):
        #     print("未找到符合条件的商品ID"+str(i['GoodsId']))
  
    
    #购买页面
    def _buynow(self):
     
        element = WebDriverWait(self.driver,3,0.3).until(
            EC.presence_of_element_located((By.CLASS_NAME, "works-offer-purchase"))
        )        
        element.click()
        _hasxpathStr = "//uni-scroll-view/div/div/div/uni-view/uni-view[3]/uni-view[2]"
        hasxpath = self.driver.find_element(By.XPATH,_hasxpathStr)
        if (hasxpath):
            raise SelfExceptionError("有订单未付款 >>>>>>>>>>>>>>>")  
            self.driver.quit()
            os._exit(0)       

        time.sleep(1)
        element2 = WebDriverWait(self.driver,3,0.3).until(     
            EC.presence_of_element_located((By.CLASS_NAME, "next"))
        )
        time.sleep(0.3)
        element2.click()
 
        #点“购买”按钮, 支付宝,要选
        try:
            element3 = WebDriverWait(self.driver,3,0.1).until(
                EC.presence_of_element_located((By.CLASS_NAME, "pay"))
            )
            time.sleep(0.3)
            element3.click()
        except:            
            if "worksdetail" in self.driver.current_url:
                print("\n\n￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣")
                print("支付失败！！！！！！,估计是账户被锁12小时。手工去查看个人中心 !!!!!\n\n")
                self.driver.quit()
                sys.exit()             
            if "cashier" in self.driver.current_url:
                print("\n\n￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣￣▽￣")
                print("已经点了立即支付，请去个人中心付款\n")
                print("⊙▽⊙ ⊙▽⊙ ⊙▽⊙ \n\n")
                self.driver.quit()
                sys.exit() 
            
            
        

#-------------------- start 
artMain()
 


